<?php
// +----------------------------------------------------------------------
// | makePHP
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://makephp.org All rights reserved.
// +----------------------------------------------------------------------
// | Licensed BSD.(http://www.make.org/BSD-license.txt)
// +----------------------------------------------------------------------
// | Author: 叁石(sanshi) <sanshi0815@tom.com>
// | Author: 白家昌<baijc2004cn@126.com>
// +----------------------------------------------------------------------

/**
 * 功能: 公用函数
 * 创建日期:Wed Oct 29 12:04:04 CST 2008
 * 最后更新:
 * 作者: sanshi 
 */

/** 重定向页面：跳转 **/
function redirectPage($url='')
{
	//$url = empty($url) ? 'history.go(-1)' : trim($url);
	//header("Location: " . $url);
	echo "<script>";
	echo true == empty($url) ? "history.go(-1);" :  "window.location='{$url}';";
	echo "</script>";
	exit();
}
/**
 * 错误处理函数，页面跳转
 * @author sanshi
 * @param string $page  跳转页面
 * @param string $msg   提示信息
 * @param  int   $h     跳转时间
 */
function jumpPage($page,$msg='',$h=0)
{
	//$msg = empty($msg)?'':"?msg=".base64_encode($msg);
	$msg = urlencode($msg);
	$msg = empty($msg)?'':"?msg={$msg}";
	$url=$page.$msg;
	if(!@header("Location:".$url))
	{
		echo "<meta http-equiv=refresh content='{$h};url=".$url."'>";
	}
	exit();
}
/**
 * 日志记录函数
 * @name   write_log
 * @param  string	log_info 	 日志描述
 * @param  string	log_type 	 日志级别
 * @param  string	log_error_no 错误号，0为没有
 * @param  string	file_name 	 发生问题的文件名，可以为空
 * @return bool 	false	写入信息
 * @access public
 * @see 	  
 * @version	1.0.0 (Wed Oct 29 11:09:03 CST 2008)
 * @author	sanshi	 
 */
function write_log ($log_info,$log_type,$log_error_no=0,$file_name="")
{

	return $false;
}
/**
 * 错误信息处理
 * @name jumpError
 * @param  int	error_no 	错误号
  * @param  int	$jump_url 	转到的url
 * @return  	
 * @access public
 * @see 	  
 * @version	1.0.0 (Wed Oct 29 11:06:28 CST 2008)
 * @author	sanshi	 
 */
function jumpError($error_no,$jump_url="",$is_admin=1)
{
	if($error_no<= -2000)
	{
		//采取js输出
		alertMsg($error_no,$jump_url);
	}else{
		global $error_object;
		//取得错误信息
		$msg = $error_object->getErrorMsg($error_no);
		if($is_admin)
		{
			$page = empty($jump_url)?ADMIN_HOST_PATH.'error.php':$jump_url;
		}else{
			$page = empty($jump_url)?HOST_PATH.'error.php':$jump_url;
		}
		//采取页面跳转
		jumpPage($page,$msg,$h=0);
	}
}
//信息提示，返回项目首页
function goToIndex($error_no)
{
	global $error_object;
	//取得错误信息
	$msg = $error_object->getErrorMsg($error_no);
	echo "<script>";
	echo "alert(' {$msg} ');";
	echo "window.location='".HOST_PATH."index.php';";
	echo "</script>";
	exit();
}
//信息提示，如果给跳转页面就跳到指定页，如果不提供，直接跳转到上一页
function alertMsg($error_no,$url = '')
{
	global $error_object;
	//取得错误信息
	$msg = $error_object->getErrorMsg($error_no);
	echo "<script>";
	echo "alert(' {$msg} ');";
	echo true == empty($url) ? "history.go(-1);" :  "window.location='{$url}';";
	echo "</script>";
	exit();
}
//信息提示，如果给跳转页面就跳到指定页，如果不提供，直接跳转到上一页
function alertMsg2($msg,$url = '')
{
	echo "<script>";
	echo "alert(' {$msg} ');";
	echo true == empty($url) ? "history.go(-1);" :  "window.location='{$url}';";
	echo "</script>";
	exit();
}
function alertMsg3($msg,$url = '')
{
	echo "<script>";
	//echo "self.parent.tb_remove();";
	echo "alert(' {$msg} ');";
	echo true == empty($url) ? "history.go(-1);" :  "window.location='{$url}';";
	echo "</script>";
	exit();
}

function getUserIP()
{
	if(isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
		$user_ip=$_SERVER["HTTP_X_FORWARDED_FOR"];
	} else {
		$user_ip=$_SERVER["REMOTE_ADDR"];
	}
	return $user_ip;
}

//截取字符串
function cutstr($string, $length, $dot = ' ...', $charset='utf-8') {
	if(strlen($string) <= $length) {
		return $string;
	}

	$string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $string);

	$strcut = '';
	if(strtolower($charset) == 'utf-8') {

		$n = $tn = $noc = 0;
		while($n < strlen($string)) {

			$t = ord($string[$n]);
			if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
				$tn = 1; $n++; $noc++;
			} elseif(194 <= $t && $t <= 223) {
				$tn = 2; $n += 2; $noc += 2;
			} elseif(224 <= $t && $t < 239) {
				$tn = 3; $n += 3; $noc += 2;
			} elseif(240 <= $t && $t <= 247) {
				$tn = 4; $n += 4; $noc += 2;
			} elseif(248 <= $t && $t <= 251) {
				$tn = 5; $n += 5; $noc += 2;
			} elseif($t == 252 || $t == 253) {
				$tn = 6; $n += 6; $noc += 2;
			} else {
				$n++;
			}

			if($noc >= $length) {
				break;
			}

		}
		if($noc > $length) {
			$n -= $tn;
		}

		$strcut = substr($string, 0, $n);

	} else {
		for($i = 0; $i < $length; $i++) {
			$strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
		}
	}

	$strcut = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);

	return $strcut.$dot;
}

//计算权限值 用户突破32位限制
function parse_power($user_power,$method_power)
{
	return  $user_power & $method_power;
}

/**
 * Enter description here...
 *
 * @param unknown_type $str
 * @return unknown
 */
function short_url($str)
{
	//return 'http://a.a/aaa';
	$short_str = file_get_contents(HOST_NAME . 'short_url_api.php?str='.$str);
	if(empty($short_str))
	{
		return false;
	}
	return $short_str;
}

/**
 * 删除html代码
 *
 * @param unknown_type $str
 * @return unknown
 */
function DeleteHtml($str)
{
	$str = trim($str);
	$str = strip_tags($str,"");
	$str = ereg_replace("\t","",$str);
	$str = ereg_replace("\r\n","",$str);
	$str = ereg_replace("\r","",$str);
	$str = ereg_replace("\n","",$str);
	$str = ereg_replace(" "," ",$str);
	return trim($str);
}


//新的截取
function cut_str($string, $sublen, $start = 0, $code = 'UTF-8')
{
    if($code == 'UTF-8')
    {
        $pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
        preg_match_all($pa, $string, $t_string);

        if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen))."...";
        return join('', array_slice($t_string[0], $start, $sublen));
    }
    else
    {
        $start = $start*2;
        $sublen = $sublen*2;
        $strlen = strlen($string);
        $tmpstr = '';

        for($i=0; $i< $strlen; $i++)
        {
            if($i>=$start && $i< ($start+$sublen))
            {
                if(ord(substr($string, $i, 1))>129)
                {
                    $tmpstr.= substr($string, $i, 2);
                }
                else
                {
                    $tmpstr.= substr($string, $i, 1);
                }
            }
            if(ord(substr($string, $i, 1))>129) $i++;
        }
        if(strlen($tmpstr)< $strlen ) $tmpstr.= "";
        return $tmpstr;
    }
}
//截取结束
/**
 * 取得卷商状态
 *
 * @return unknown
 */
function get_securities_arr()
{
	global $securities_arr;
	return $securities_arr;
}

/** 获取redis配置 **/
function get_redis_servers()
{
	global $redis_servers;
	return $redis_servers;
}

/** 获取redis配置前缀标识 **/
function get_redis_prefix()
{
	global $redis_prefix;
	return $redis_prefix;
}

// 浏览器友好的变量输出
function dump($var, $echo=true,$label=null, $strict=true)
{
    $label = ($label===null) ? '' : rtrim($label) . ' ';
    if(!$strict) {
        if (ini_get('html_errors')) {
            $output = print_r($var, true);
            $output = "<pre>".$label.htmlspecialchars($output,ENT_QUOTES)."</pre>";
        } else {
            $output = $label . " : " . print_r($var, true);
        }
    }else {
        ob_start();
        var_dump($var);
        $output = ob_get_clean();
        if(!extension_loaded('xdebug')) {
            $output = preg_replace("/\]\=\>\n(\s+)/m", "] => ", $output);
            $output = '<pre>'. $label. htmlspecialchars($output, ENT_QUOTES). '</pre>';
        }
    }
    if ($echo) {
        echo($output);
        return null;
    }else
        return $output;
}

/** json_encode 输出 **/
function make_json($code, $msg='', $data=array(), $is_echo = 1)
{
	$tmp = array('code'=>$code, 'msg'=>$msg, 'data'=>$data);
	$result = json_encode($tmp);
	if($is_echo) {
		echo $result;
		exit;
	} else {
		return $result;
	}	
}
/**
 * 输出json格式信息（暂时只有发帖和转发接口同步使用）
 *
 * @param unknown_type $code
 * @param unknown_type $msg
 */
function interface_make_json($code, $msg='')
{
	$tmp = array('code'=>$code, 'msg'=>$msg);
	echo json_encode($tmp);
	exit;
}
/**
 * 取得维修记录状态
 *
 * @return unknown
 */
function get_mend_state_arr()
{
	global $mend_state_arr;
	return $mend_state_arr;
}
/**
 * 取得购置性质
 *
 * @return unknown
 */
function get_sell_type_arr()
{
	global $sell_type_arr;
	return $sell_type_arr;
}
/**
 * 取得是否存在子设备
 *
 * @return unknown
 */
function get_is_exist_c_mc()
{
	global $is_exist_c_mc;
	return $is_exist_c_mc;
}
/**
 * 取得币种数组
 *
 * @return unknown
 */
function get_price_type_arr()
{
	global $price_type_arr;
	return $price_type_arr;
}
/**
 * 取得付款方式
 *
 * @return unknown
 */
function get_pay_type_arr()
{
	global $pay_type_arr;
	return $pay_type_arr;
}
/**
 * 取得运送方式
 *
 * @return unknown
 */
function get_transport_type()
{
	global $transport_type_arr;
	return $transport_type_arr;
}
/**验收结果**/
function get_auth_result()
{
	global $auth_result_arr;
	return $auth_result_arr;
}
//供货厂商
function get_company_arr()
{
	global $company_arr;
	return $company_arr;
}
//到货地址
function get_area_arr()
{
	global $area_arr;
	return $area_arr;
}

/**
 * (功能描述) 获取自定义配置文件数组内容
 *
 * @param 
 * @return
 */
function get_custom_conf($name= '')
{
	if(empty($name)) {
		return array();
	}
	
	global $$name;
	$configName = $$name;
	return is_array($configName) ? $configName : array();
}

// 循环创建目录
function mk_dir($dir, $mode = 0777) {
    if (is_dir($dir) || @mkdir($dir, $mode))
        return true;
    if (!mk_dir(dirname($dir), $mode))
        return false;
    return @mkdir($dir, $mode);
}

function get_mc_type()
{
	global $mc_type;
	return $mc_type;
}
/**
 * 获得今天第多少周
 *
 * @return unknown
 */
function get_today_week()
{
	return date('W');
}

function get_week_date($week=1,$year)
{
    $timestamp = mktime(1,0,0,1,1,$year);
    $firstday = date("N",$timestamp);
    if($firstday >4)
        $firstweek = strtotime('+'.(8-$firstday).' days', $timestamp);
    else
        $firstweek = strtotime('-'.($firstday-1).' days', $timestamp);
    
    $monday = strtotime('+'.($week - 1).' week', $firstweek);
    $sunday = strtotime('+6 days', $monday);
    
    $start = date("Y-m-d", $monday);
    $end   = date("Y-m-d", $sunday);
    
    return array($start, $end);	
}
?>